<template>
    <div class="addBrand-container">
      <el-page-header @back="goBack" :content="content" style="margin-bottom:20px">
      </el-page-header>
    <div class="container">
      <el-form ref="ruleForm"
               :model="ruleForm"
               :inline="false"
               label-width="180px"
               class="demo-ruleForm">
        <el-form-item label="图片:"
                      prop="image">
          <uploadImage class="uploadImage" :imageUrl="ruleForm.image" @imageUrl2="imageUrl2" />
        </el-form-item>
        <el-form-item label="商店名称:"
                      prop="name">
          <el-input v-model="ruleForm.name"
                    placeholder="请输入商店名称"
                     />
        </el-form-item>
        <el-form-item label="地址:"
                      prop="phone">
          <el-input v-model="ruleForm.address"
                    placeholder="请输入地址"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    style="width: 295px;"
                     />
        </el-form-item>
        <!-- <el-form-item label="店主:">
          <el-select v-model="ruleForm.userId" placeholder="商店" >
            <el-option :label="user.name" :value="user.id" v-for="(user,index) in users" :key="index"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="店主:">
          <!-- 使用 el-autocomplete 需要将数据改成{ "value": "xxx(在输入建议看到的值，必需)", "address": "看自身情况" },-->
          <el-autocomplete
            class="inline-input"
            v-model="shopkeeper"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <div class="subBox address">
          <!-- <el-form-item> -->
          <el-button @click="() => $router.push('/home/store')">
            取消
          </el-button>
          <el-button type="primary"
                     :class="{ continue: actionType === 'add' }"
                     @click="submitForm(actionType)">
            保存
          </el-button>
          <!-- <el-button v-if="actionType == 'add'"
                     type="primary"
                     @click="submitForm('ruleForm', true)">
            保存并继续添加
          </el-button> -->
          <!-- </el-form-item> -->
        </div>
      </el-form>
    </div>
  </div>
</template>


<script>
import uploadImage from '@/components/upload/uploadImage.vue'
import {addUser,updateUser,userPage} from '@/api/user'
import {storePage,queryById,addStore, updateStore} from '@/api/store'
export default{
  components:{
    uploadImage
  },
  data() {
    return {
      content:'添加商店',
      ruleForm:{
        name: '',
        id:'',
        userId:this.$route.query.userId,
        address:'',
        image:'',
        status:0
      },
      rules:'',
      actionType:'',
      users:[],
      user:this.$route.query.user,
      restaurants: [],
      shopkeeper: '',
    }
  },
  created(){
    let res;
    this.actionType = this.$route.query.methods
    this.shopkeeper = this.$route.query.shopkeeper
    this.ruleForm.userId =  this.$route.query.userId
    userPage(null,1,100,this.$route.query.id).then((res)=>{
      this.restaurants = []
      this.users = res.data.records
      //forEach构造this.restaurants
      res.data.records.forEach((data)=>{
        let user = {
          value:data.name,
          id:data.id
        }
        this.restaurants.push(user)
      })
      //map构造this.restaurants
      // this.restaurants = this.users.map((terminal)=>{
      //   return {
      //     value: name,
      //     id:id,
      //   }
      // })
    })
    if(this.actionType == 'add'){
      this.content='添加商店'
    }else{
      this.content='修改商店信息'
      res = queryById(this.$route.query.id)
      res.then((res)=>{
        // this.ruleForm =  Object.assign(res.data)
        //根据对象已有的参数进行复制
        Object.keys(this.ruleForm).forEach(key => {
          this.ruleForm[key] = res.data[key] == undefined ? this.ruleForm[key] : res.data[key]
      })
      }).catch((err)=>{
        this.$message.error(err)
      })
      
    }
    //查询所有store
    const res2 = storePage('',1,10)
    res2.then((res)=>{
      console.log(res.data)
      this.stores = res.data.records
    }).catch((err)=>{
      this.$message.error(err)
    })
    
  },
  mounted(){
    

  },
  methods:{
    querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        }
      },
      handleSelect(item) {
        this.ruleForm.userId = item.id
        this.user = this.users.find((user)=>{
          return user.id == item.id
        })
        console.log(this.user);
      },
      async submitForm(value){
      console.log(this.ruleForm)
      let res;
      if(value == 'add'){
        let newStore;
        await addStore(this.ruleForm).then((res)=>{
          newStore = res.data
        }).catch((err)=>{
          this.$message.error(err);
        })
        //修改员工职位 修改员工所属商店
        this.user.roleId = 3
        this.user.storeId = newStore.id
        updateUser(this.user).then((res)=>{
          this.$message({
              message: '添加成功',
              type: 'success'
            });
            this.$router.push('/home/store')
        }).catch((err)=>{
          this.$message.error(err);
        })
      }

      else if(value == 'update'){
        console.log(value)
        console.log(this.ruleForm)
        var user2 = this.$route.query.user
        await updateStore(this.ruleForm).then((res)=>{
          this.newStore = res.data
          console.log(this.user.id)
        console.log(this.$route.query.userId)
        //修改员工职位 修改原店主职位
        if(this.user.id != this.$route.query.userId){
          this.user.roleId = 3
          console.log(2)
          console.log(this.user)
          updateUser(this.user).then((res)=>{
          
            console.log(user2)
            user2.roleId = 4
            console.log(3)
            updateUser(user2).then((res)=>{
              console.log(4)
              this.$message({
                  message: '更新成功',
                  type: 'success'
                });
              // console.log(res)
              this.$router.push('/home/store')
            }).catch((err)=>{
              this.$message.error(err)
            })
          }).catch((err)=>{
            this.$message.error(err)
          })
        }else{
          this.$message({
                  message: '更新成功',
                  type: 'success'
                });
          this.$router.push('/home/store')
        }

        }).catch((err)=>{
          console.log(err)
          this.$message.error(err);
        })

        





      }
    },
    goBack(){
      this.$router.go(-1)
    },
    imageUrl2(imageUrl2){
          console.log('imageUrl2:'+imageUrl2)
          this.ruleForm.image = imageUrl2
    }
  }
}
</script>

<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 30px;
    margin-top: 0px;
    .HeadLable {
      background-color: transparent;
      margin-bottom: 0px;
      padding-left: 0px;
    }
    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;

    }
    .idNumber {
      margin-bottom: 39px;
    }

    .el-form-item {
      margin-bottom: 29px;
    }
    .el-input {
      width: 293px;
    }
  }
}

.demo-ruleForm{
  width: 600px;
}

.uploadImage{
  border-radius: 5px;
}
</style>